//
//  LTFContentCollectionViewCell.m
//  NeteaseNews
//
//  Created by liutaifeng on 16/4/19.
//  Copyright © 2016年 liutaifeng. All rights reserved.
//

#import "LTFVideoContentCollectionViewCell.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>
#import "LTFContentTableViewCell.h"
#import "LTFVideoModel.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "MJRefresh.h"
#define WIDTH self.contentView.frame.size.width
#define HEIGHT self.contentView.frame.size.height
@interface LTFVideoContentCollectionViewCell ()
<
 UITableViewDataSource,
 UITableViewDelegate
>


@property (nonatomic, retain) MPMoviePlayerViewController *moviePlayer;
@property (nonatomic, retain) UIView *playView;
@property (nonatomic, assign) NSInteger tags;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *tableViewArray;
@property (nonatomic, retain) NSMutableArray *topicArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger down;
@property (nonatomic, retain) NSString *judge;
@property (nonatomic, retain) NSString *docPath;
@end


@implementation LTFVideoContentCollectionViewCell
- (instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        [self createView];
        [self setupRefreshView];
        
    }
    return self;
}
- (void)setupRefreshView
{

    //1.下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //2.上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadNewData
{
    self.page = 0;
    [self createData];
    
}



- (void)loadMoreData
{
    [self createData];
}
- (void)setStr:(NSString *)str {
    if (_str != str) {
        [_str release];
        _str = [str retain];
        [self create];

        self.playView.hidden = YES;
        [self.playView removeFromSuperview];
    }
}
- (void)create {
    if (self.str != nil) {
        NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES) lastObject];
        self.docPath = [sandBox stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", self.str]];
    
        NSDictionary *unarchiver = [NSKeyedUnarchiver unarchiveObjectWithFile:_docPath];
        if (unarchiver == nil) {
            [self createData];
        }
        else {
            NSArray *array = [unarchiver objectForKey:[NSString stringWithFormat:@"%@", self.str]];
            self.tableViewArray = [LTFVideoModel BaseModelByArray:array];
        }
    }
}

- (void)createView {
    self.page = 0;
     self.tableViewArray = [NSMutableArray array];
    [self create];
    //tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    [self addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;//注册
    self.tableView.rowHeight = 300;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[LTFContentTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LTFContentTableViewCell class])];
    self.tableView.tag = 1002;
    self.tableView.contentOffset = CGPointMake(0, 0);
    
    // 创建一个透明度为0的view, 用来承接视频
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(12, 50, WIDTH - 24, 300 / 2 + 30)];
    self.playView.backgroundColor = [UIColor blackColor];
    [self.tableView addSubview:self.playView];
    self.playView.hidden = YES;
    [_playView release];
    
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.button.tag = 666;
    _button.frame = CGRectMake(WIDTH / 4 * 3 - 20, 0, 20, 20);
    _button.backgroundColor = [UIColor redColor];
    
    [_button setBackgroundImage:[UIImage imageNamed:@"x.png"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
}



//tableView的第一个协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableViewArray.count;
}
//tableView的第二个协议
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LTFContentTableViewCell class]) forIndexPath:indexPath];
    LTFVideoModel *model = self.tableViewArray[indexPath.row];
    cell.title.text = model.title;
    [cell.picImageView setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"zhenwei.png"]];
    cell.timeAndCountLabel.text = [NSString stringWithFormat:@"%02d:%02d / %.2f万播放", [model.length intValue] / 60, [model.length intValue] % 60, [model.playCount intValue] / 10000.0];
    [cell.headImageView setImageWithURL:[NSURL URLWithString:model.topicImg] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.nameLabel.text = model.topicName;
    if ([model.replyCount intValue] != 0) {
        cell.replyLabel.text = [NSString stringWithFormat:@"%@", model.replyCount];
    }
    cell.tag = 2000 + indexPath.row;
    return cell;
}

// 在cell的点击方法中找到cell的坐标
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.playView.hidden = NO;
    LTFContentTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.tags = cell.tag;
    self.playView.frame = CGRectMake(cell.frame.origin.x + 12, cell.frame.origin.y + 60, cell.frame.size.width - 24, cell.frame.size.height / 2 + 30);
    LTFVideoModel *model = self.tableViewArray[indexPath.row];
    
    self.moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    self.moviePlayer.view.frame = CGRectMake(0, 0, self.playView.frame.size.width, self.playView.frame.size.height);
    
    [self.moviePlayer.moviePlayer setScalingMode:MPMovieScalingModeAspectFill];
    [self.moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleEmbedded];
    [self.playView addSubview:self.moviePlayer.view];
    [_moviePlayer release];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.playView.hidden == NO) {
        LTFContentTableViewCell *cell = (LTFContentTableViewCell *)[scrollView viewWithTag:self.tags];
       CGFloat y = scrollView.contentOffset.y - cell.frame.origin.y - cell.frame.size.height;
        if (y > 0) {
            [[self.tableView superview] addSubview:self.playView];
            self.playView.frame = CGRectMake(WIDTH / 4, HEIGHT - 150 - 64, WIDTH / 4 * 3, 150);
            [self.playView addSubview:_button];
        }
        else {
            [self.tableView addSubview:self.playView];
            self.playView.frame = CGRectMake(cell.frame.origin.x + 12, cell.frame.origin.y + 60, cell.frame.size.width - 24, cell.frame.size.height / 2 + 30);
            [_button removeFromSuperview];
        }
    }
    

}
- (void)click:(UIButton *)button {
    self.playView.hidden = YES;
    [button removeFromSuperview];
    [self.playView removeFromSuperview];
}


- (void)layoutSubviews {
    self.tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
}

- (void)createData {
    
        NSString *string = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/Tlist/%@/%ld-10.html", self.str, self.page];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:string parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = responseObject;
            [NSKeyedArchiver archiveRootObject:dic toFile:_docPath];
            NSArray *array = [dic objectForKey:[NSString stringWithFormat:@"%@", self.str]];
            if ([self.judge isEqualToString:self.str]) {
                [self.tableViewArray addObjectsFromArray:[LTFVideoModel BaseModelByArray:array]];
                
            }
            else {
                self.tableViewArray = [LTFVideoModel BaseModelByArray:array];
            }
            self.page += 10;
            // 刷新表格
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView reloadData];
            self.judge = self.str;
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
